package com.lin.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lin.dto.Params;
import dto.SysUserDto;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import service.IdWorker;
import service.UserService;
import util.ResponseVo;

import java.util.List;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController extends BaseController{
    @Reference
    UserService userService;
    @Reference
    private IdWorker idWorker;

    @PostMapping("/list")
    public ResponseVo list(Params params, SysUserDto user){
        PageHelper.startPage(params.getPage(),params.getPageSize());
        List<SysUserDto> users = userService.findUserMsg(user);

        PageInfo<SysUserDto> userPageInfo = new PageInfo<>(users);

        return this.pageData(userPageInfo);
    }

    @PostMapping("/add")
    @RequiresPermissions("user_add")
    public ResponseVo addUser(SysUserDto user,Long[] roles) {
        user.setUserId(idWorker.nextId());
        if(user.getStatus().equalsIgnoreCase("true")){
            user.setStatus("1");
        }else{
            user.setStatus("2");
        }
        userService.addUser(user,roles);
        return ResponseVo.ok("success");
    }

    @GetMapping("/userwithrole")
    public ResponseVo getUserWithRole(SysUserDto user){

        return ResponseVo.ok(userService.findUserWithRole(user));
    }

    @PostMapping("/update")
    @RequiresPermissions("user_edit")
    public ResponseVo updateUser(SysUserDto user, Long[] roles, BindingResult bindingResult){
        if(user.getStatus().equalsIgnoreCase("true")){
            user.setStatus("1");
        }else{
            user.setStatus("2");
        }
        userService.updateUser(user, roles);
        return ResponseVo.ok("修改成功");
    }
    @PostMapping("/delete")
    @RequiresPermissions("user_delete")
    public ResponseVo deleteUser(SysUserDto user){
        userService.deleteUser(user);
        return ResponseVo.ok("删除成功");
    }

}
